import axios from 'axios'
import store from './store'
import router from './router'
// token 要放在所以的http请求header之上
// const LOGOUT = 'LOGOUT'
export default function serAxios () {
  axios.interceptors.request.use(
    config => {
      if (store.state.token) {
        config.headers.token = store.state.token
      }
      return config
    }
  )

  // 获取数据code是-1则认为登录过期，需要重新登录
  axios.interceptors.response.use(
    response => {
      if (response.status === 200) {
        const data = response.data
        if (data.code === -1) {
          // 注销登录，清空vuex和localstorage
          store.commit('settoken', '')
          localStorage.removeItem('token')
          // 跳转login
          router.replace({
            path: '/login'
          })
        }
        return data
      }
      return response
    }
  )
}
